package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Buy;
import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.mapper.BuyMapper;
import cn.wolfcode.trip.base.mapper.CommodityMapper;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.query.BuyQueryObject;
import cn.wolfcode.trip.base.service.IBuyService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private BuyMapper buyMapper;
    @Autowired
    private SignMapper signMapper;
    @Autowired
    private CommodityMapper commodityMapper;

    @Override
    public PageInfo<Buy> query(BuyQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Buy> list = buyMapper.query(qo);
        return new PageInfo<Buy>(list);
    }

    @Override
    public boolean setStatus(Long id) {
        Buy buy = buyMapper.selectByPrimaryKey(id);
        if (buy.getStatus()==Buy.STATUS_NORMAL){
            buyMapper.setStatus(id);
            return true;
        }
        return false;
    }

    @Override
    public void delete(Long id) {
        buyMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Buy getAddress(Long id) {
        return buyMapper.getAddress(id);
    }

    @Override
    public void saveOrUpdate(Buy buy) {
        if (buy.getId() == null) {
            buyMapper.insertAddress(buy);
        }else {
            buyMapper.updateAddress(buy);
        }
    }

    @Override
    public void saveShop(Buy buy) {
        JSONResult result = new JSONResult();
        Commodity commodity = commodityMapper.selectByPrimaryKey(buy.getCommodity().getId());
        Sign sign = signMapper.getSign(buy.getUser().getId());
        if (sign.getIntegral()>commodity.getDiscountPrice()){
            Buy address = buyMapper.getAddress(buy.getUser().getId());
            buy.setName(address.getName());
            buy.setSite(address.getSite());
            buy.setTel(address.getTel());
            buy.setTime(new Date());
            buyMapper.saveShop(buy);
            int money = (sign.getIntegral()-commodity.getDiscountPrice());
            sign.setIntegral(money);
            signMapper.updateByPrimaryKey(sign);
        }else {
            throw new RuntimeException("您的积分不足");
        }
    }

    @Override
    public Buy get(Long id) {
        return buyMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Integer> prices(int status) {
        return buyMapper.prices(status);
    }
}
